package com.report.reportserver.controller;

import com.report.reportserver.service.ExportExcelService;
import com.report.reportserver.service.SysSqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ ClassName: ExportDataController
 * @ Description：数据导出文件api控制器
 * @ Modified By：
 * @ Version:
 * @ Author     ：LiYing
 * @ Date       ：Created in 13:42 2022/4/21
 */

@Controller
@RequestMapping(value = "/file")
public class ExportDataController {

    @Autowired
    ExportExcelService exportExcelService;
    @Autowired
    SysSqlService sqlService;

    @RequestMapping(value = "/exceltable")
    @ResponseBody
    public void getUserInfoEx(String tableName, HttpServletResponse response) {
        try {
            //查询表中的所有数据
            List<Map<String, Object>> dataList = new ArrayList<>();
            List<Object[]> tempList = sqlService.selectTableData(tableName);

            //查询表中的列名信息
            Map map = sqlService.getTableInfoMap(tableName);
            List list = (List<Object>) map.get("columnList");

            ArrayList<String> titleKeyList = new ArrayList<>();//列名集合
            Object[] a;
            for (Object o : list) {
                a = (Object[]) o;
                String keyId = a[0].toString();
                titleKeyList.add(keyId);
            }

            //将JPA查询到的表中的List<Object[]>转为List<Map<String, Object>>
            for (Object[] b : tempList) {
                Map<String, Object> m = new HashMap<>();
                for (int i = 0; i < b.length; i++) {
                    m.put(titleKeyList.get(i), b[i]);
                }

                dataList.add(m);
            }

            exportExcelService.exportDataToExcel(titleKeyList, dataList, tableName, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
